﻿. "./common.ps1"

# Paths
$packFolder = (Get-Item -Path "./" -Verbose).FullName
$packStoreFolder = "C:/EasyXafNugetPackages"
$rootFolder = Join-Path $packFolder "../"

$release = 'Release';
if ($args.Count -gt 0) {
    if($args.Contains("--debug") -or $args.Contains("-d")) {
        $release = 'Debug'
    }
	
	$projectParamIndex = $args.IndexOf("-p")
    if($projectParamIndex -gt -1 -and $args.Count -ge $projectParamIndex) {
        $projects = ($args[$projectParamIndex + 1])
    }
}

if(-not (Test-Path $packStoreFolder)) {
    mkdir $packStoreFolder
}

# Rebuild all solutions
foreach($solution in $solutions) {
    $solutionFolder = Join-Path $rootFolder $solution
    Set-Location $solutionFolder
    & dotnet restore
}

# Create all packages
foreach($project in $projects) {
    
    $projectFolder = Join-Path $rootFolder $project
	$releaseFolder = Join-Path $projectFolder ("bin/" + $release)
	
    # Create nuget pack
    Set-Location $projectFolder 
	
	if (Test-Path $releaseFolder) {
		Remove-Item -Recurse ($releaseFolder)
	}
	
    dotnet pack -c ($release)

    if (-Not $?) {
        Write-Host ("Packaging failed for the project: " + $projectFolder)
        exit $LASTEXITCODE
    }
    
    # Copy nuget package
    $projectName = $project.Substring($project.LastIndexOf("/") + 1)
    $projectPackPath = Join-Path $releaseFolder ($projectName + ".*.nupkg")
	
    Move-Item $projectPackPath $packStoreFolder -Force
}

# Go back to the pack folder
Set-Location $packFolder